import base64
from datetime import datetime

from pymongo import DESCENDING
from pytz import timezone

from client.openai_client import invoke_laozhangapi_only_result
from model.wristband_models import WarningData, AudioData
from utils.aliyun_token_util import send_asr
from utils.mongo_util import db


def b64_to_amr_bytes(voice_b64: str) -> bytes:
    """把 JSON 里的 voice 字段转成 AMR 原始字节"""
    return base64.b64decode(voice_b64)


async def handle_audio(data: AudioData):
    str = send_asr(b64_to_amr_bytes(data.audio.voice))
    answer = await invoke_laozhangapi_only_result(f'我下面的话要判断他的意思，你就输出一个单词，'
                                                  f'如果是表示收到了就输出2，表示完成了，'
                                                  f'就输出3，如果表示拒绝就输出0，'
                                                  f'没有以上三种含义就输出-1 不用多说任何一个字。 {str}')
    if answer != '-1':
        date = datetime.fromtimestamp(data.timestamp, timezone('Asia/Shanghai'))
        if answer == '2':
            db.s_clean_keeping_order.find_one_and_update(
                {"handler.imei": data.device_id, 'state': int(answer)}, {"$set": {'state': 3,
                                                                                  'handlingTime': date,
                                                                                  'handlingMessage': str}},
                sort=[("createDate", DESCENDING)])
        if answer == '3':
            db.s_clean_keeping_order.find_one_and_update(
                {"handler.imei": data.device_id, 'state': int(answer)}, {"$set": {'state': 4,
                                                                                  'completionTime': date,
                                                                                  'completionMessage': str}},
                sort=[("createDate", DESCENDING)])
        print(answer)
